/**
 * 去掉遮罩层，解决bootstrap关闭弹出框后，遮罩层不关闭的bug
 */
function removePopup($modal){
	$modal.on('hide.bs.modal', function () {
		$(this).remove();
	})
}
/**
 * 解决长页面fixed无法向下滚动
 */
function fixedScroll(_window, $e){
	$(_window)
		.off('scroll')
		.on('scroll',function(){
			$e.css('top', 0 - $(_window).scrollTop());
		});
}
/**
 * 弹出框相关
 */
function fun_popup_confirm(message){
	var dtd = $.Deferred();
	var $popup = $('.js_popup_confirm', top.document)
		.clone(true)
		.removeClass("js_popup_confirm")
		.addClass("js_popup_confirm_clone");
	removePopup($popup)
	$popup
		.appendTo(top.document.body)
		.find(".modal-body").empty().html(message)
		.end()
		.find(".js-submit").on("click",function(){
			dtd.resolve();
        })
        .end()
        .find(".js-js-close").on("click",function(){
        	dtd.reject();
        })
        .end()
		.modal('show');
	return dtd.promise();
}

function fun_popup_message(message){
	if(!message){
		return;
	}
	var dtd = $.Deferred();
	var $popup = $('.js_popup_message', top.document)
		.clone(true)
		.removeClass("js_popup_message")
		.addClass("js_popup_message_clone");
	removePopup($popup);
	$popup
		.appendTo(top.document.body)
		.find(".modal-body").empty().html(message)
		.end()
		.find(".js-submit").on("click",function(){
			dtd.resolve();
        })
        .end()
		.modal('show');
	return dtd.promise();
}

function fun_popup_common($this, title, body, width, height, closeFreshFLag, openCallback, closeCallback){
	width = width ? width : "700";
	height = height ? height : 60;
	var size = {};
	if(width != "auto"){
		size.width = width;
	}
	if(height != "auto"){
		size.height = height;
	}
	//
	var $popup = $('.js_popup_prompt', top.document)
		.clone(true)
		.removeClass("js_popup_prompt")
		.addClass("js_popup_prompt_clone")
		.appendTo(top.document.body);
	removePopup($popup);
	var $body = $popup
			.find(".modal-dialog")
//			.css("width", width)
		.end()
			.find(".modal-title").text(title)
		.end()
			.find(".modal-body").empty().html(body)
			.css(size);
//			.css("width", width).css("height", height);
	var $content = $body.children();
	//
	$popup
		// 打开
		.off('shown.bs.modal')
		.on('shown.bs.modal', function () {
			openCallback && openCallback.call($content, $body);
		})
		.modal({backdrop: 'static'})	// 禁止点击空白时自动关闭
		// 关闭
		.off('hide.bs.modal')
		.on('hide.bs.modal', function () {
				closeCallback && closeCallback.call($content, $body);
				//
				$popup.remove()
				// 刷新页面
				if(closeFreshFLag){
					location.reload()
				}
				// myDataFind处理
				$this
					.closestCom("myDataFind")
					.fireBind("bind")
			});
	//
	fixedScroll(top, $popup);
}

/**
 * iframe 加载成功后执行
 */
function onload_operateIframe(iframe){
	var $iframe = $(iframe);
	// 兼容获取iframe的document
	var $doc = $(getIframeDoc(iframe));
	// 去掉下边滚动条
	$doc
		.find("body")
		.css({"overflow-x":"hidden" , "overflow-y":"auto"});
	// 更改取消按钮的功能
	var $popup = $iframe.closest(".js_popup_prompt_clone");
	removePopup($popup);
	var $popup_iframeContainer_close = $popup.find('.modal-footer .js-close');
	$doc
		.find(".js_forEmbedPopup_cancel")
		.attr("href", "javascript:void(0);")
		.on("click", function(){
			// 关闭对话框
			$popup_iframeContainer_close.trigger('click');
			// $popup_iframeContainer.modal('hide');	// .appendTo(top.document.body) 导致无效
		});
	// 重设背景
	$doc.find("body")
		.css("background-color", "#fff")
		.css("padding", "10px")
	// 保存iframe自身弹出框容器的句柄
	$doc[0].iframeContainerClose = $popup_iframeContainer_close;
	// 重置iframe高度
	showIframeAllHeight(iframe);
}

/**
 * iframe相关
 */
function embedsIsContainsOperate_fun(this_, closeFreshFLag){
	var $this = $(this_);
//	var width = 1250, height = 500;
	var width = "auto", height = "auto";
	$this
		.attrExist("popupWidth", function(n, v){
			width = v;
		})
		.attrExist("popupHeight", function(n, v){
			height = v;
		});
	var url = $this.attr("src");
	// 处理表单提交方式
	var iframeName = Math.random();
	// 处理myForm标签
	var $myForm;
	if($this.hasClass('js_withData')){
		$myForm = $this.closest(".js_module").findCom("myForm");
		$myForm.attr("target", iframeName);
		$myForm.attr("access",url)
		url = "";
	}
	var $iframe = $("<iframe width='100%' src='"+url+"' name='"+iframeName+"' frameborder='0' ></iframe>");
	// 调用弹出框
	fun_popup_common(
			$this,
			$this.text(), 
			"", 
			width, 
			height, 
			closeFreshFLag,
			function($body){
				$iframe
					.on('load',function() {
						if($iframe.data("firstLoad") !== true){
							$iframe.data("firstLoad", true)
							$myForm && $myForm.fireBind('bind')
						}
						onload_operateIframe($iframe[0])
					})
					.appendTo($body);
			},
			function($body){
				// 清理iframe
				clearIframe($iframe[0]);
			}
		);
}

function clearIframe(iframe){
	var iframeWin = getIframeWin(iframe);
	iframe.src = 'about:blank';
	try{
		iframeWin.document.write('');
		iframeWin.document.clear();
	}catch(e){};
     //以上可以清除大部分的内存和文档节点记录数了
     //最后删除掉这个 iframe 就哦咧。
	var $parent = $(iframe).parent();
	$parent[0].removeChild(iframe);
}

function getIframeWin(iframe){
	return iframe.contentWindow || iframe.contentDocument.parentWindow;
}

function getIframeDoc(iframe){
	return iframe.document || iframe.contentWindow.document;
//	var $doc = $(iframe.document);	// IE
//	if($doc.length<=0){
//		$doc = $(iframe.contentWindow.document); // 火狐
//	}
}

function showIframeAllHeight(iframe) {
	if (iframe) {
		var iframeWin = getIframeWin(iframe);
		if (iframeWin.document.body) {
			iframe.height = getScrollInfo(getIframeDoc(iframe)).scrollHeight;
			iframe.height = Number(iframe.height) + 50;
			// 重新设置top的滚动条长度
			$(top.document.body).height(iframe.height)
		}
	}
}

/**
	对于document.compatMode，很多朋友可能都根我一样很少接触，知道他的存在却不清楚他的用途。今天在ext中看到 document.compatMode的使用，感觉这个对于我们开发兼容性的web页面还是很有帮助，我们都知道，IE对盒模型的渲染在 Standards Mode和Quirks Mode是有很大差别的，在Standards Mode下对于盒模型的解释和其他的标准浏览器是一样，但在Quirks Mode模式下则有很大差别，而在不声明Doctype的情况下，IE默认又是Quirks Mode。所以为兼容性考虑，我们可能需要获取当前的文档渲染方式。
	document.compatMode正好派上用场，它有两种可能的返回值：BackCompat和CSS1Compat，对其解释如下：
	BackCompat Standards-compliant mode is not switched on. (Quirks Mode)
	CSS1Compat Standards-compliant mode is switched on. (Standards Mode)
	在实际的项目中，我们还需要在获取浏览是否IE，这样就可以得到IE的渲染模式了。在Ext中的代码：isBorderBox=isIE&&!isStrict。
	当文档有了标准声明时， document.compatMode 的值就等于 "CSS1compat"， 因此， 我们可以根据 document.compatMode 的值来判断文档是否加了标准声明
	var height = document.compatMode=="CSS1Compat" ? document.documentElement.clientHeight : document.body.clientHeight;
	BackCompat：标准兼容模式关闭。
	CSS1Compat：标准兼容模式开启。
**/
function getScrollInfo(_document){
	var obj = {};
	if (_document.compatMode == "BackCompat") {
		obj.scrollWidth = _document.body.scrollWidth;
		obj.scrollHeight = _document.body.scrollHeight;
		obj.scrollLeft = _document.body.scrollLeft;
		obj.scrollTop = _document.body.scrollTop;
	}else { //document.compatMode == "CSS1Compat"
		obj.scrollWidth = _document.documentElement.scrollWidth;
		obj.scrollHeight = _document.documentElement.scrollHeight;
		obj.scrollLeft = _document.documentElement.scrollLeft == 0 ? _document.body.scrollLeft : _document.documentElement.scrollLeft;
		obj.scrollTop = _document.documentElement.scrollTop == 0 ? _document.body.scrollTop : _document.documentElement.scrollTop;
	}
	return obj;
}

function getClientInfo(_document){
	var obj = {};
	if (_document.compatMode == "BackCompat") {
		obj.clientWidth = _document.body.clientWidth;
		obj.clientHeight = _document.body.clientHeight;
	}else { //document.compatMode == "CSS1Compat"
		obj.clientWidth = _document.documentElement.clientWidth;
		obj.clientHeight = _document.documentElement.clientHeight;
	}
	return obj;
}

function iframeHeightOnresize(iframe){
	if(iframe){
		var iframeWin = getIframeWin(iframe);
		// iframe自身 body 监听onresize事件
		//iframeWin.window.document.body.onresize = function(){
			// 重置父iframe高度
			$("iframe.embedIframe",window.parent.document).each(function(){
					showIframeAllHeight(this);
				})
		//}
	}
}

/**
 * 列表排序相关
 */
function js_orderScript(){
    var $this = $(this);
    var $parentFindCom = $(this).closestCom("myDataFind");
    var output = $this.getFirer('bind').outputData();
    if(!output.order){
		return;
	}
    var orderWay = output.order.orderWay;
    var orderBy = output.order.orderBy;
    var $defaultOrderBy = $parentFindCom.find("th.js_orderButton_"+orderBy)
    var $sort = $defaultOrderBy.find('.js_sorting');
    if(orderWay=='DESC'){
    	$sort.removeClass('glyphicon-sort').addClass('glyphicon-arrow-down')
    }else if(orderWay=='ASC'){
    	$sort.removeClass('glyphicon-sort').addClass('glyphicon-arrow-up')
    }
}
function js_order(th){
	var $this = $(th);
	var $parentFindCom = $this.closestCom("myDataFind");
    var orderBy = $this.attr("orderby");
    var isASC = $this.find('.js_sorting').hasClass('glyphicon-arrow-up');
    var $OrderBys = $parentFindCom.find("th.js_orderButton").find('.js_sorting')
        .removeClass('glyphicon-arrow-up').removeClass('glyphicon-arrow-down').addClass('glyphicon-sort')
    //
    if(isASC){
    	$parentFindCom.find(".js_orderWay").val("DESC")
    	$parentFindCom.find(".js_orderBy").val(orderBy)
    }else{
    	$parentFindCom.find(".js_orderWay").val("ASC")
        $parentFindCom.find(".js_orderBy").val(orderBy)
    }
}

/*
 * 文件上传插件配置
 */
function fileuploadConfig(){
	var $imgUpload = $(".fileuploadPlus");
	var show = $imgUpload.attr("show");
	// 配置
	var initConig = {
				language : 'zh',
				// 显示相关
				showUpload : false, 
				showCaption : false,
				showClose : false,
				showRemove : true,
				showBrowse : true,
				// 初始化预览相关
				initialPreviewShowDelete : false,
				initialPreviewFileType: 'image'
				// overwriteInitial: true,
			};
	if(show && show!='null'){
		initConig.initialPreview = [
			"<img width='100%' src='"+show+"' class='file-preview-image' >"
		];
	}
	// 初始化
	$imgUpload
		.fileinput(initConig)
		.on('fileclear', function(event) {
			$(this).fileinput("refresh")
			refreshConfig();
		})
	//设置预览容器
	function refreshConfig(){
		$(".file-preview")
			.css({
				"width": "330px",
				"height": "330px",
				"background-size": "100%",
				"background-position": "center",
				"background-image": "url(/resources/images/initShow.png)"
			})
			.show()
	}
	refreshConfig()
}

function fileuploadShowConfig(){
//	var $imgUpload = $(".fileuploadPlus-show");
	var $imgUpload = $(this);
	var show = $imgUpload.attr("show");
	// 配置
	$imgUpload
		.fileinput({
			language : 'zh',
			// 显示相关
			showUpload : false, 
			showCaption : false,
			showClose : false,
			showRemove : false,
			showBrowse : false,
			// 初始化预览相关
			initialPreviewShowDelete : false,
			initialPreviewFileType: 'image',
			overwriteInitial: false,
			initialPreview : [
				"<img width='100%' src='"+show+"' class='file-preview-image' >"
			]
		})
}

/**
 * 模块相关
 */
function fireMyDataFind_forModule(message){
	var $this = $(this);
	$.when(fun_popup_message(message))
		.done(function(){
			$this
				.closest(".js_module")
				.findCom("myDataFind")
				.fireBind("bind")
		})
}

/**
 * 权限相关
 */
function js_checked(thisTarget){
	$(thisTarget)
		.closest(".panel")
		.find(".panel-body input")
		.prop("checked", $(thisTarget).prop("checked"));
}

/**
 * 操作相关
 */
/* 提交成功 */
function fun_bindAfterAction(returnTypeParaName, actionType, message){
	var $this = $(this);
	if(inIframePopup()){
		switch(actionType){
			case 'Delete':
				// iframeContainer 来自 project.js 文件下 onload_operateIframe 函数
				return $.when(fun_popup_message(message))
					.done(function(){
						document.iframeContainerClose.trigger('click')
					});
			case 'Add':
			case 'Edit':
			case 'Post':
			case 'Put':
				if($this.attr("bindAfterTo")==""){
					return $.when(fun_popup_message(message))
						.done(function(){
							document.iframeContainerClose.trigger('click')
						});
				}
			default:
				var newUrl = UUrl($this.attr("bindAfterTo"))
					 .setPara(returnTypeParaName, "Popup")
					 .get();
				$this.attr("bindAfterTo", newUrl)
				return fun_popup_message(message);
		}
	}else{
		return fun_popup_message(message);
	}
}

function fun_setReferrerOperateTarget($this, isPopup, referrerOperateTarget){
	if(isPopup){
		$this.attr(
				"src",
				UUrl($this.attr("src"))
					.setPara("sys_referrer_operateTarget", referrerOperateTarget)
					.get()
			);
	}else{
		$this.attr(
				"href",
				UUrl($this.attr("href"))
					.setPara("sys_referrer_operateTarget", referrerOperateTarget)
					.get()
			);
	}
}
function fun_ReferrerType(_this, isPopup){
	var $this = $(_this);
	if(inIframe()){
		if(inIframePopup()){	// 所在页为弹出框式iframe
			fun_setReferrerOperateTarget($this, isPopup, "Popup");
		}else{					// 所在页为嵌入式iframe
			fun_setReferrerOperateTarget($this, isPopup, "Embed");
		}
	}
}

/**
 * 判断是否在弹出框中
 */
function inIframePopup(){
	return inIframe() && !obtainOwnerIframe().hasClass("embedIframe");
}

/**
 * 判断是否在iframe中
 */
function inIframe(){
	return self!=top;
}

function obtainOwnerIframe(){
//	$(window.frameElement).is("iframe") // true
	return $(window.frameElement);
}

/**
 * 过滤相关
 */
function advancedFilterStart(_this){
	var $find = $(_this).closestCom('myDataFind');
	$find
		.find('.advancedFilterPopup')
//		.on('shown.bs.modal', function () {		// 弹出高级过滤时设置高级过滤为当前过滤器
//			$find.find('.baseFilter').removeClass('currentFilter');
//			$find.find('.advancedFilter').addClass('currentFilter');
//		})
//		.on('hidden.bs.modal', function () {	// 关闭高级过滤时设置基础过滤为当前过滤器
//			$find.find('.advancedFilter').removeClass('currentFilter');
//			$find.find('.baseFilter').addClass('currentFilter');
//		})
		.modal('show')
}

function baseFilterStart(){
	var $find = $(this);
	var $firer = $find.getFirer('bind');
	if($firer.closestCom("myFilter").hasClass("baseFilter")){
		$find.find('.advancedFilter').removeClass('currentFilter');
		$find.find('.baseFilter').addClass('currentFilter');
	}
}

/**
 * 提交高级过滤时执行
 */
function advancedFilterSubmit(_this){
	$(_this).closestCom('myDataFind')
		.find('.baseFilter')
		.removeClass('currentFilter')
	.end()
		.find('.advancedFilter')
		.addClass('currentFilter');
}

/**
 * 查找模块相关
 */
function function_checkbox(_this){
	var $this = $(_this);
	$this.parent().children().not($this).prop("checked", $this.prop("checked"));
}

function function_myDataFind(){
	$(this).find("thead :checkbox").prop("checked", false)
}

/**
 * select列表再过滤
 */
function js_listReFilter_onfocus(_this){
	var $input = $(_this);
	var $select = $input.parent().find("select");
	$select.show();
	var amount = $select.find("option").length;
	amount = amount > 8 ? 8 : amount;
	$select.attr('size', amount);
	// 过滤 option
	$select.find("option").not(".js_option_default").each(function(i,v){
		var $option = $(this);
		if($option.text().search($input.val()) == -1){
			$option.hide();
		}else{
			$option.show();
		}
	});
}

function js_listReFilter_onblur_input(_this){
	var $input = $(_this);
	var inputVal = $input.val();
	var $select = $input.parent().find("select");
	if(!$(event.relatedTarget).is($select)){
		$select.hide();
	}
	if($select.val() === null || $select.val() === ""){
		$input.val(null);
	}else{
		$select.find("option").not(".js_option_default").each(function(i,v){
			var $option = $(this);
			if($option.val() === $select.val()){
				$input.val($option.text());
			}
		});
	}
}

function js_listReFilter_click_option(_this){
	var $option = $(_this);
	var $select = $option.parent();
	var $input = $select.parent().find("input");
	$select.hide();
	if($option.val()!==""){
		$input.val($option.text())
	}else{
		$input.val("");
	}
}

function js_listReFilter_onkeyup_input(_this){
	var $input = $(_this);
	var $select = $input.parent().find("select");
	if($input.val() === ""){
		$select.val(null);
	}
	// 过滤 option
	$select.find("option").not(".js_option_default").each(function(i,v){
		var $option = $(this);
		if($option.text().search($input.val()) == -1){
			$option.hide();
		}else{
			$option.show();
		}
	});
}

/**
 * page 点击图片显示大图
 */
function fun_showBigImg(_this){
	fun_popup_message("<img width='200' src='" + $(_this).attr("src") + "' />")
}